package org.rency.mq.activemq.jms.support.impl;

import org.rency.mq.activemq.constant.DestinationType;
import org.rency.mq.activemq.jms.support.DestinationResolver;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;
import java.util.HashMap;
import java.util.Map;

public class DestinationResolverImpl implements DestinationResolver {

    private Map<String, Destination> cachedDestination = new HashMap<String, Destination>();
    private static DestinationResolver destinationResolver = new DestinationResolverImpl();

    private DestinationResolverImpl() {
    }

    public static DestinationResolver getInstance() {
        return destinationResolver;
    }

    public Destination getDestination(Session session, String destinationName,int destinationType) throws JMSException {
        Destination destination = cachedDestination.get(destinationName);

        if (destination == null) {
            if (destinationType == DestinationType.QUEUE) {
                destination = session.createQueue(destinationName);
            } else if (destinationType == DestinationType.TOPIC) {
                destination = session.createTopic(destinationName);
            }

            cachedDestination.put(destinationName, destination);
        }

        return destination;
    }

    public Destination resolveDestinationName(Session session,String destinationName, boolean pubSubDomain) throws JMSException {
        Destination destination = cachedDestination.get(destinationName);

        if (destination == null) {
            if (pubSubDomain) {
                destination = session.createTopic(destinationName);
            } else {
                destination = session.createQueue(destinationName);
            }

            cachedDestination.put(destinationName, destination);
        }

        return destination;
    }
}
